package com.dearbinge.pay.util;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.request.*;
import com.alipay.api.response.*;
import com.dearbinge.data.pojo.orderTable.OrderTable;
//import com.xunruhuyu.distributed.pojo.order.Orders;
//import com.xunruhuyu.distributed.pojo.order.PaymentParamBean;
//import com.xunruhuyu.distributed.pojo.ordernew.Order;
//import com.xunruhuyu.distributed.utils.Configure;


public class AlipayUtil {

    // App支付 调取地址
    private static String alipayServerURL ="https://openapi.alipay.com/gateway.do";
    /**
    *	商户id 更换商户需要换到商户id 公钥私钥
    */
//    private static String app_id="2018062160355850";
    private static String app_id="2018091961437362";
    /**
    *	应用私钥  对交易数据进行加签
    */
    private static String private_key="MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCFNd38ZE0K2rZ2IfWikRj4YDDQd2C2oFghCC+h4qBHd9S70M0MkmUf+IoSPIM7hr+b1EP+ZRyQKMDSirHC2L4tIfacS58hlzrVPkZnsKLZhjtcBwa4WVbmPyvs6Nel7w8mpfyt/WDinF30Vssmi3YHsDutvSLNxQ4iHaEzdCGtTbNGmiuAMezKvcVQ3omws6+e1skpG/eO/qUgd0Qcz7sZSIIJMYZON3dgQpz2VXuo+DkyJxrGiBis7yum4uFLZbWWUelUy/7U8vmgEC7qoOqAo3UVvR5R3iwmslvY3w3F4cPERZKrSXrvXR9GGyJqD3NzzJmmKwULOoEaNYJcsAwpAgMBAAECggEAFrTG4PWr2DTNszc4qnw3GGc1CuO+XYLZYtAFZn+9uFDptxXxTbpKeHeh+VfNOsFOOd6ltGBBzSTVMU4o3MCbMhA+/Ac72brwcVbLI3ONXqytw5MDBztbP6X288wAri0glQLoHjQ5Zocm0LZWrHxLIyZcFdJOc2qqbRBF4QJjlymNLTv2ZlT1yM8iHr1MDX3xmYFx9QoyjHFXDo1rPoVer8Rty+PZlm3wI5PExri09CDl9Qz6VkzwUXEJxLneE9zbtbKl3BxKMFCP0ap7rJZRRhtsFQh8vHYD0aCsa/bvo1eLl2qKtHXKnBDFAPGOHZje6yy7wG4hDOmUWMW0VOpLAQKBgQDxq2hG63nVtr/1V/WZpkRVUGRp1KfysaV/IUonNzpYfMPcNjz/xiyQoQSJL5lB8REWxNuh/QYlmvOjWhmCWF0HsybKeG5dWXQwoWaW6ZFoptT1Xkn3BCRYqfbM+1+4L2P7NgcvPl7KZfI8JanfXIWcy5cP6v6N4RSSHuAd30e8CQKBgQCNHAc1N5/F6cf7sypedQrigv5EUrsdh/Dprt2wY37agd0XqnJq7v6JTgOnsOKA4LhznwZqY6M1xXqrEdSyNgsMqD3x8zXFrTTx9tdN6d6Js5DlIm8OiDbl2f3O+I22Sf3vFEGYCqmVEC4/paqBhQxWBpwuv7yfPp7+zxqEiSwXIQKBgBv7IKO1d/HKqwcZHBKiMZ8/I6EtQhTThLnnfNJ1jofYSkUg8ocaxuYn/oJzxGbiJnxgZp2m0iNggX0UXYe9+2d80qz2rLCaPt2yklI+0NsxFc8jD6VOEXdClpS9NiP5OLZJVyOdMRR2IUndgoGeEMpKuD7bkoWS3fLdKE3NIF0hAoGBAISuoRxqFCKtguxp+GHe3gBEub8Wp3jKFT41vaAYvfPJ/lE9ZN6loNMMdyVbjm8uXmHhWs/4pkNuT7zBRGTZqiQZoj15ucsI5WrK9oH9cNG79XdunExmym/wPNY7Ik0QX+RJALBs/i36i/Iu3RdyOjo9dugCQ+Lcp/XiWQXcUYfhAoGACek+2FNqSqDoQKw/k50NvCGtxvoGZSMQ1pfkBEmRtJlvPWgH5WADszpMbUEULdIf0s1/lgwHK4urNYaW1+L1qzCTSA9lHYgL4YjKDCYUBvL+vMrx73hc4Y+u3t3zlzIwmdCD11yuqXKfbRcgdKixIJYQGUeLBrPtj8TrZiP4V5A=";
    /**
     *	支付宝公钥 对交易结果进行验签
     */
    private static String alipay_public_key="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAt1KNh8ixW09mFabIFRxrd11diLrs90uMP8wn2pE47vIPZ21oJLzWcfWzcbYKozF+C719rcP9BhvAeFV0fYdBCk5Fe18yuBEAgpGAhNQMG84vJ7mihSzPlJT1rigUPVI33GX7WH8tXtb/dcGHe4BjxGprP9mc6YDzDQFNJSoAyZJH0L/+LP29P75INiCQc5YNys0wdZOQLOWKAWWNywXsVEjv3Lca2+rGaXFklfuykQ98flSNuv+stR0r603p/0W0Cajd1Vfd8R36Dj+mieonUuBQr0rf0V5eEbxfyYUvLzi13ohbZUg1GIyFO9cKfGfHz+Nwpm/FwNYLFQ5b9gnbGwIDAQAB";
    /**
     * 支付宝回调地址 统一在 config.properties 管理
     */
    public static String notify_url="https://www.so.com";
    private static String format="json";
    private static String charset="UTF-8";
    private static String sign_type="RSA2";
    private static String timeoutExpress="30m";
    private static String productCode="QUICK_MSECURITY_PAY";



    /**
     * 调用支付宝   统一收单线下交易预创建
     * @param orders 订单对象
     * @param paymentParam
     * @return 加签后的字符串
     */
    public static String alipayCreate(OrderTable orders) {
    	try {
    		String method= "alipay.trade.precreate";
            AlipayClient alipayClient = new DefaultAlipayClient(alipayServerURL,app_id,private_key,format,charset,alipay_public_key,sign_type);
            AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
            request.setBizContent("{" +
                    "\"method\":\""+method+"\"," +
                    "\"out_trade_no\":\"123456789\"," +
                    "\"total_amount\":\"0.01\"," +
                    "\"subject\":\"UWE购火箭充值\"" +
                    "  }");
            AlipayTradeQueryResponse response = alipayClient.execute(request);
            if(response.isSuccess()){
                System.out.println("调用成功");
                System.out.println(response.toString());
            } else {
                System.out.println("调用失败");
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 调用支付宝    加签功能
     *
     * @param orders 订单对象
     * @param paymentParam
     * @return 加签后的字符串
     */
    public static String payment(OrderTable orders) {

    	//设置支付宝回调地址
//        notify_url = Configure.getValue("alipay.notify_url");
//
//        alipay_public_key =paymentParam.getAlipayPublicKey();
//        private_key = paymentParam.getAlipayPrivateKey();
//        app_id =paymentParam.getAlipayAppId();

        //实例化客户端

    	/*  URL	          支付宝网关（固定）     		https://openapi.alipay.com/gateway.do
    		APP_ID	APPID即创建应用后生成	获取见上面创建应用并获取APPID
    		APP_PRIVATE_KEY	开发者应用私钥，由开发者自己生成	获取见上面配置密钥
    		FORMAT	参数返回格式，只支持json	json（固定）
    		CHARSET	请求和签名使用的字符编码格式，支持GBK和UTF-8	开发者根据实际工程编码配置
    		ALIPAY_PUBLIC_KEY	支付宝公钥，由支付宝生成	获取详见上面配置密钥
    		SIGN_TYPE	商户生成签名字符串所使用的签名算法类型，目前支持RSA2和RSA，推荐使用RSA2	RSA2*/
        AlipayClient alipayClient = new DefaultAlipayClient(alipayServerURL, app_id, private_key, format, charset, alipay_public_key, sign_type);
        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();

        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();

        model.setBody("UWE购火箭充值");
//        model.setBody(orders.getOrderBody());
        //显示的订单信息
        model.setSubject("123456789");
//        model.setSubject(orders.getOrderSetCount());
        //唯一订单号
        model.setOutTradeNo("123456789");
//        model.setOutTradeNo(orders.getOrderNo());
        //金额
//        model.setTotalAmount(orders.getOrderTotalAmount()+ "");
        model.setTotalAmount(0.01+ "");
        model.setTimeoutExpress(timeoutExpress);
        model.setProductCode(productCode);
        request.setBizModel(model);

        //回调地址
        request.setNotifyUrl(notify_url);
        try {
            //这里和普通的接口调用不同，使用的是sdkExecute
            AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
            System.out.println("toString : "+response.toString());
            System.out.println(response.getBody());//就是orderString 可以直接给客户端请求，无需再做处理。
            return response.getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        return null;
    }


    /**
     * 调用支付宝 统一收单线下 交易查询
     * @param orderNo
     * @return
     */
    public static String tradeQuery(String orderNo){
        try {
            AlipayClient alipayClient = new DefaultAlipayClient(alipayServerURL,app_id,private_key,format,charset,alipay_public_key,sign_type);
            AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
            request.setBizContent("{" +
                    "\"out_trade_no\":\""+orderNo+"\"," +
                    //"\"trade_no\":\"2014112611001004680 073956707\"" +
                    "  }");
            AlipayTradeQueryResponse response = alipayClient.execute(request);
            if(response.isSuccess()){
                System.out.println("调用成功");
                System.out.println(response.toString());
            } else {
                System.out.println("调用失败");
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 调用支付宝统一收单    交易关闭接口
     * @param orderNo
     * @return
     */
    public static String tradeClose(String orderNo){
        try {
            AlipayClient alipayClient = new DefaultAlipayClient(alipayServerURL,app_id,private_key,format,charset,alipay_public_key,sign_type);
            AlipayTradeCloseRequest request = new AlipayTradeCloseRequest();
            request.setBizContent("{" +
                    //"\"trade_no\":\"2013112611001004680073956707\"," +
                    "\"out_trade_no\":\""+orderNo+"\"," +
                    "\"operator_id\":\"YX01\"" +
                    "  }");
            AlipayTradeCloseResponse response = alipayClient.execute(request);
            if(response.isSuccess()){
                System.out.println("调用成功");
                System.out.println(response.toString());
            } else {
                System.out.println("调用失败");
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 调用支付宝统一收单    交易退款接口
     * @param orders
     * @return
     */
//    public static String tradeRefund(Orders orders){
//        try {
//            AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do","app_id","your private_key","json","GBK","alipay_public_key","RSA2");
//            AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
//            request.setBizContent("{" +
//                    "\"out_trade_no\":\""+orders.getOrderNo()+"\"," +
//                    //"\"trade_no\":\"2014112611001004680073956707\"," +
//                    "\"refund_amount\":"+orders.getOrderTotalAmount()+"," +
//                    "\"refund_currency\":\"USD\"," +
//                    "\"refund_reason\":\"正常退款\"," +
//                    "\"out_request_no\":\"HZ01RF001\"," +
//                    "\"operator_id\":\"OP001\"," +
//                    "\"store_id\":\"NJ_S_001\"," +
//                    "\"terminal_id\":\"NJ_T_001\"," +
//                    "      \"goods_detail\":[{" +
//                    "        \"goods_id\":\"apple-01\"," +
//                    "\"alipay_goods_id\":\"20010001\"," +
//                    "\"goods_name\":\"ipad\"," +
//                    "\"quantity\":1," +
//                    "\"price\":2000," +
//                    "\"goods_category\":\"34543238\"," +
//                    "\"body\":\"特价手机\"," +
//                    "\"show_url\":\"http://www.alipay.com/xxx.jpg\"" +
//                    "        }]," +
//                    "      \"refund_royalty_parameters\":[{" +
//                    "        \"royalty_type\":\"transfer\"," +
//                    "\"trans_out\":\"2088101126765726\"," +
//                    "\"trans_out_type\":\"userId\"," +
//                    "\"trans_in_type\":\"userId\"," +
//                    "\"trans_in\":\"2088101126708402\"," +
//                    "\"amount\":0.1," +
//                    "\"amount_percentage\":100," +
//                    "\"desc\":\"分账给2088101126708402\"" +
//                    "        }]" +
//                    "  }");
//            AlipayTradeRefundResponse response = alipayClient.execute(request);
//            if(response.isSuccess()){
//                System.out.println("调用成功");
//                System.out.println(response.toString());
//            } else {
//                System.out.println("调用失败");
//            }
//        } catch (AlipayApiException e) {
//            e.printStackTrace();
//        }
//        return null;
//    }

    //trade.fastpay.refund.query(统一收单交易退款查询)

    /**
     * 调用支付宝统一收单    交易退款查询
     * @param orderNo
     * @return
     */
    public static String tradeFastpay(String orderNo){
        try {
            AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do","app_id","your private_key","json","GBK","alipay_public_key","RSA2");
            AlipayTradeFastpayRefundQueryRequest request = new AlipayTradeFastpayRefundQueryRequest();
            request.setBizContent("{" +
                    //"\"trade_no\":\"20150320010101001\"," +
                    "\"out_trade_no\":\""+orderNo+"\"," +
                    "\"out_request_no\":\""+orderNo+"\"" +
                    "  }");
            AlipayTradeFastpayRefundQueryResponse response = alipayClient.execute(request);
            if(response.isSuccess()){
                System.out.println("调用成功");
                System.out.println(response.toString());
            } else {
                System.out.println("调用失败");
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return null;
    }
}